package echo;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;

@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in=(ByteBuf)msg;
        System.out.println("有人说:"+in.toString(CharsetUtil.UTF_8));
        ChannelFuture channelFuture = ctx.writeAndFlush(in);
        channelFuture.addListener((ChannelFutureListener) channelFuture1 -> {
            if(channelFuture1.isSuccess()){
                System.out.println("发送成功");
            }else {
                System.out.println("发送失败");
                channelFuture1.cause().printStackTrace();//打印错误
            }
        });

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();//打印异常栈
        ctx.close();//关闭连接
    }
}
